<template>
	<view class="page-wrap" :data-theme="theme" :style="globalColor.style" :class="['step' + step, theme]">
		<template v-if="!isApp">
			<HeadCustom title="发布文章" :isAppBtn="false" :isHome="!isApp"></HeadCustom>
		</template>
		<view class="wrap" v-if="step == 0">
			<view class="gather gather-text">
				<!-- <view class="hd font32 lh44">采集文章</view> -->
				<view class="bd">
					<textarea
						maxlength="500"
						v-model="text"
						class="text"
						placeholder="长按粘贴微信公众号或今日头条文章链接在此处，请勿转发谣言、暴 力、色情、辱骂等违规内容"
					></textarea>
				</view>
			</view>
			<view class="gather gather-tips">
				<view class="hd font32 lh44">温馨提示</view>
				<view class="bd mt20 font28 color-contentFontFourColor lh40">
					<view class="fboxRow Ycenter item">
						<text class="num fboxRow Ycenter Xcenter">1</text>
						从微信公众号或今日头条找到好文章
					</view>
					<view class="fboxRow Ycenter item">
						<text class="num fboxRow Ycenter Xcenter">2</text>
						复制文章链接
					</view>
					<view class="fboxRow Ycenter item">
						<text class="num fboxRow Ycenter Xcenter">3</text>
						粘贴至上方输入框内，点击【采集】
					</view>
					<view class="fboxRow Ycenter item">
						<text class="num fboxRow Ycenter Xcenter">4</text>
						采集成功后，发布
					</view>
					<view class="fboxRow Ycenter item">
						<text class="num fboxRow Ycenter Xcenter">5</text>
						查看并转发分享
					</view>
					<view class="fboxRow Ycenter item mt10">
						<u-icon name="error-circle" color="#747986"></u-icon>
						本功能只限采集微信公众号或今日头条文章
					</view>
				</view>
			</view>
		</view>
		<view class="wrap" v-if="step == 1">
			<view class="fboxRow Ycenter gather-analyze">
				<image
					class="pic"
					src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/single/icon-link.png"
					mode="aspectFill"
				></image>
				<view class="state font32" v-if="loading">正在解析链接...</view>
				<view class="state font32" v-else>文章采集失败，请重试</view>
				<!-- <view class="close" @click="step = 0"><u-icon name="close-circle-fill" color="#454D61" size="18"></u-icon></view> -->
			</view>
		</view>
		<view class="" v-if="step == 2">
			<view class="article hotAricle bui-article">
				<view class="title font38">{{ detail.title }}</view>
				<view class="info fboxRow font24">
					<text class="txt_msg">{{ detail.editTime }}</text>
					<text v-if="detail.author" class="txt_msg">作者：{{ detail.author }}</text>
					<text v-if="detail.articleSource" class="txt_msg">
						来源：{{ detail.articleSource }}
					</text>
				</view>
				<!-- <view class="userInfo fboxRow" v-if="userInfo">
					<image class="avatar" :src="userInfo.imagePhoto" mode="aspectFill"></image>
					<view class="line"></view>
					<view class="fboxCol detail_msg">
						<view class="name font32 flex1">{{userInfo.realName}}</view>
						<view class="flex1 font28 user_msg mt24" v-if="userInfo.firstCompanyName">
							<text class="bw-Vector8 bwfont icon_txt"></text>
							{{userInfo.firstCompanyName}}
						</view>
						<view class="flex1 font28 user_msg mt10" v-if="userInfo.firstPositionName">
							<text class="bw-a-zu3478 bwfont icon_txt"></text>
							{{userInfo.firstPositionName}}
						</view>
					</view>
				</view> -->
				<view class="detail">
					<view
						id="contentEditor"
						class="font32 content"
						v-html="detail.newContent"
						style="white-space: pre-wrap"
					></view>
					<view class="reminder font28">
						以上文章内容，不代表本无名片平台观点，内容授权、投诉请联系
						benwu@benwunet.com
					</view>
				</view>
			</view>
		</view>
		<BottomFixed>
			<template v-if="step == 0">
				<view
					class="fboxRow Ycenter Xcenter btn border-radius12 font32 color-selectedFontColor btn-preview"
					@click="clearTap"
				>
					清空
				</view>
				<button
					class="fboxRow Ycenter Xcenter flex1 btn font32 border-radius12 bg-linear"
					@click="nextTap"
					:loading="loading"
					hover-class="none"
				>
					采集{{ loading ? '中' : '' }}
				</button>
			</template>
			<!-- <template v-if="step == 1">
				<view v-if="!loading" class="fboxRow Ycenter Xcenter flex1 btn font32 border-radius12 bg-linear" @click="prevTap">返回</view>
			</template> -->
			<template v-if="step == 2">
				<button
					class="fboxRow Ycenter Xcenter flex1 btn font32 border-radius12 bg-linear"
					@click="enterTap"
					:loading="enterLoading"
					hover-class="none"
				>
					发布
				</button>
			</template>
		</BottomFixed>
		<!-- <u-tabbar :fixed="true" :placeholder="true" :safeAreaInsetBottom="true">
			<view class="bottom-btn fboxRow Ycenter">
				<template v-if="step == 0">
					<view class="fboxRow Ycenter Xcenter btn border-radius12 font32 color-selectedFontColor btn-preview" @click="clearTap">清空</view>
					<button class="fboxRow Ycenter Xcenter flex1 btn font32 border-radius12 bg-linear" @click="nextTap" :loading="loading">
						采集{{loading ? '中' : ''}}
					</button>
				</template>
				<template v-if="step == 1">
					<view v-if="!loading" class="fboxRow Ycenter Xcenter flex1 btn font32 border-radius12 bg-linear" @click="prevTap">返回</view>
				</template>
				<template v-if="step == 2">
					<button class="fboxRow Ycenter Xcenter flex1 btn font32 border-radius12 bg-linear" @click="enterTap" :loading="enterLoading">
						发布
					</button>
				</template>
			</view>
		</u-tabbar> -->
	</view>
</template>
<script>
import ArticleItem from './components/article-item.vue';
import HeadMore from '@/components/head-custom/head-more.vue';
import BottomFixed from '@/components/bottom-btn/fixed.vue';
import { hotTextDetail, hotQuote, hotTextPublish, hotTextUrl } from '@/api/h5';
import { detailStyleList, putCardStyleUpdate, cardMine } from '@/api/card.js';
import { utf8to16, base64decode } from '@/static/js/Base64.js';
import { getRequest, debounce } from '@/static/js/common.js';
import { fileAnonoUploadMpc, fileUploadAnon } from '@/api/index.js';
// 引入编辑器
import './components/Eleditor-master/jquery.min.js';
import './components/Eleditor-master/Eleditor.min.js';
import './components/Eleditor-master/webuploader.min.js';
import './components/Eleditor-master/layout/base.css';
export default {
	components: { ArticleItem, HeadMore, BottomFixed },
	data() {
		return {
			theme: getApp().globalData.appTheme,
			globalColor: getApp().globalData.globalColor,
			isAction: false,
			detail: {},
			userInfo: {},
			userList: [],
			userIndex: '',
			text: '',
			isApp: true,
			id: '',
			pageType: 0,
			step: 0,
			loading: false,
			enterLoading: false,
			contentEditor: null,
			imgObj: {},
			timer: null
		};
	},
	onLoad(option) {
		if (option && option.benwu) {
			let benwu = utf8to16(base64decode(option.benwu));
			this.benwu = option.benwu;
			const token = {
				// access_token: getRequest(benwu,'token'),
				// id: getRequest(benwu,'id'),
				statusBarHeight: getRequest(benwu, 'statusBarHeight')
				// authStatus: getRequest(benwu,'authStatus'),
			};
			if (getRequest(benwu, 'token')) {
				token.access_token = getRequest(benwu, 'token');
			}
			getApp().globalData.statusBarHeight = token.statusBarHeight;
			uni.setStorageSync('bw_params', JSON.stringify(token));
		}
		if (option && option.isApp) {
			this.isApp = option.isApp == 1 ? true : false;
		} else {
			const { bw_link } = getApp().getBWData(['bw_link']);
			this.isApp = bw_link.isApp == 1 ? true : false;
		}
		if (option.pageType) {
			this.pageType = option.pageType;
		}
		if (option.url) {
			this.step = 1


			this.text = decodeURI(option.url); //app 传递参数存在中文，app进行编码，h5解码
			this.nextTap();
		}
	},
	onShow() {
		const hotArticleTemp = getApp().globalData.hotArticleTemp;
		if (
			hotArticleTemp &&
			(hotArticleTemp.title || hotArticleTemp.content || hotArticleTemp.img)
		) {
			this.step = 2;
			this.detail = hotArticleTemp;
			// this.getUser()
		}
	},
	mounted() {
		// #ifdef H5
		window.appFileCallback = this.appFileCallback;
		// #endif
	},
	onUnload() {
		clearInterval(this.timer);
		this.timer = null;
	},
	methods: {
		// 初始化编辑器以及配置
		initEditor() {
			const _this = this;
			var contentEditor = new Eleditor({
				el: '#contentEditor',
				uploader: function () {
					// return new Promise((_resolve, _reject) => {
					// 	uni.chooseFile({
					// 		count: 1,
					// 		type: 'image',
					// 		extension: ['.png', '.jpg', '.webp'],
					// 		success(res) {
					// 			uni.showLoading({
					// 				title: '上传中...',
					// 				icon: 'loading',
					// 				mask: true
					// 			});
					// 			// tempFilePath可以作为img标签的src属性显示图片
					// 			const tempFilePaths = res.tempFiles;
					// 			fileUploadAnon(tempFilePaths[0])
					// 				.then(res => {
					// 					_resolve(res.data.url);
					// 				})
					// 				.finally(() => {
					// 					uni.hideLoading();
					// 				});
					// 		}
					// 	});
					// });
				},
				/*初始化完成钩子*/
				mounted: function () {},
				changer: function () {
					_this.$set(_this.detail, 'content', contentEditor.getContent());
				},
				// const _this = this
				/*自定义按钮的例子*/
				toolbars: [
					'insertText',
					'editText',
					// 'insertImage',
					{
						id: 'insertImage',
						// tag: 'p,img', //指定P标签操作，可不填
						name: '插入图片',
						handle: function (select, controll) {
							contentEditor.saveState();
							const newContentEditor = contentEditor;
							const data = { type: 'fileUpload', action: 'contentImg' };

							_this.$bridge.callHandler('recruitHandler', data, (res) => {
								console.log('recruitHandler', '返回');
								_this.appFileCallback(res);
							});
							_this.timer = null


							clearInterval(_this.timer);
							_this.timer = setInterval(() => {
								if (_this.imgObj.action) {
									clearInterval(_this.timer);
									_this.timer = null;
									newContentEditor
										.getEditNode()
										.after(
											$(
												`<img src=${_this.imgObj.fileUrl} style="max-width:100%;height:auto"/>`
											)
										);
									_this.imgObj = {};
									_this.$set(_this.detail, 'content', contentEditor.getContent());
									contentEditor.hideEditorControllerLayer();
									// return true;
								}
							}, 1000);

							return false;
						}
					},
					'insertLink',
					'insertHr',
					'delete',
					//自定义一个视频按钮
					{
						id: 'insertVideo',
						// tag: 'p,img', //指定P标签操作，可不填
						name: '插入视频',
						handle: function (select, controll) {
							contentEditor.saveState();
							const newContentEditor = contentEditor;
							const data = { type: 'fileUpload', action: 'contentVideo' };

							_this.$bridge.callHandler('recruitHandler', data, (res) => {
								console.log('recruitHandler', '返回');
								_this.appFileCallback(res);
							});
							_this.timer = null;
							_this.timer = setInterval(() => {
								if (_this.imgObj.action) {
									clearInterval(_this.timer);
									_this.timer = null;

									newContentEditor
										.getEditNode()
										.after(
											$(
												`<video src=${_this.imgObj.fileUrl} style="max-width:100%;height:auto" x5-video-orientation="portraint" x5-video-player-type="h5" x5-video-player-fullscreen="true" type="video/mp4" controls poster= ${_this.imgObj.mpc_url}><video>`
											)
										);
									_this.imgObj = {};
									_this.$set(_this.detail, 'content', contentEditor.getContent());
									contentEditor.hideEditorControllerLayer();
									// return true;
								}
							}, 1000);

							// uni.chooseFile({
							// 	count: 1,
							// 	type: 'video',
							// 	extension: ['.mp4'],
							// 	success: async res => {
							// 		uni.showLoading({
							// 			title: '上传中...',
							// 			icon: 'loading',
							// 			mask: true
							// 		});
							// 		// tempFilePath可以作为img标签的src属性显示图片
							// 		const tempFilePaths = res.tempFiles;
							// 		if (tempFilePaths[0].size > 50 * 1024 * 1024) {
							// 			uni.showToast({
							// 				title: '视频大小不能超过50M',
							// 				icon: 'none'
							// 			});
							// 			return;
							// 		}

							// 		await fileAnonoUploadMpc(tempFilePaths[0])
							// 			.then(res => {
							// 				newContentEditor
							// 					.getEditNode()
							// 					.after(
							// 						$(
							// 							`<video src=${
							// 								res.data.url
							// 							} style="max-width:100%;height:auto" x5-video-orientation="portraint" x5-video-player-type="h5" x5-video-player-fullscreen="true" type="video/mp4" controls poster= ${
							// 								res.data.mpc_url
							// 							}><video>`
							// 						)
							// 					);
							// 			})
							// 			.finally(() => {
							// 				// 视频上传时 不会触发 编辑器的changer,所以需要自己写
							// 				_this.$set(_this.detail, 'content', contentEditor.getContent());
							// 				// 消除弹出的编辑器
							// 				contentEditor.hideEditorControllerLayer();
							// 				uni.hideLoading();
							// 			});
							// 	}
							// });

							/*注意！！！在编辑修改内容前务必通过saveState保存下状态，这样编辑器撤销按钮才会生效，否则无法撤销修改*/

							/*.getEditNode()拿到的是一个jq节点对象，插入到已选择的节点后面*/

							/*!!!!!!返回false编辑面板不会关掉*/

							// !!!在执行完上面代码之前，编辑器不能关闭，否则拿不到dom节点
							return false;
						}
					},
					'undo',
					'cancel'
				]
				//placeHolder: 'placeHolder设置占位符'
			});
		},
		appFileCallback(res) {
			const obj = res;
			this.imgObj = obj;
		},
		// 关联信息
		getUser() {
			cardMine().then((res) => {
				this.userInfo = res.data;
			});
			// const { bw_user_temp } = getApp().getBWData(['bw_user_temp'])
			// if (bw_user_temp && bw_user_temp.memberId) {
			// 	this.userInfo = bw_user_temp
			// 	// detailStyleList({cardId: bw_user_temp.memberId}).then(res=>{
			// 	// 	res.data.filter(item=>{
			// 	// 		item.check = false
			// 	// 	})
			// 	// 	this.userList = res.data
			// 	// })
			// }
		},
		previewTap() {
			getApp().globalData.hotArticleTemp = this.detail;
			this.$pageTo(`/hotArticle/detail?preview=1&id=hotArticleTemp`);
		},
		clearTap() {
			this.text = '';
		},
		prevTap() {
			this.step = 0;
		},
		nextTap: debounce(function (event) {
			if (this.text) {
				// this.step = 1
				this.loading = true;
				hotTextUrl({ url: this.text })
					.then((res) => {
						res.data.newContent = res.data.content.replace('677px', '100%');
						if (res.data.title || res.data.content || res.data.img) {
							this.getUser();
							this.detail = res.data;
							this.step = 2;
							// 需要等文章采集完成才初始化编辑器，不然拿不到dom节点
							this.$nextTick(() => {
								this.initEditor();
							});
						} else {
							this.loading = false;
							uni.showToast({
								icon: 'none',
								title: '请复制头条或者微信公众号的文章！'
							});
							this.hotArticleGather('请复制头条或者微信公众号的文章！');
						}
						// if(res.code == 0){
						// 	// this.getUser()
						// }
					})
					.catch((err) => {
						this.loading = false;
						uni.showToast({
							icon: 'none',
							title: err.message
						});
						this.hotArticleGather(err.message);
					});
			} else {
				uni.showToast({
					icon: 'none',
					title: '请粘贴需要采集的微信公众号或今日头条文章链接'
				});
				this.hotArticleGather('请粘贴需要采集的微信公众号或今日头条文章链接');
			}
		}, 2000),
		hotArticleGather(msg) {
			const data = {
				type: 'hotArticleGather',
				message: msg
			};
			this.$bridge.callHandler('appHandler', data, () => {
				console.log('recruitHandler', '返回');
			});
		},
		enterTap: debounce(function (event) {
			// 关联信息时需要去修改名片样式，产品需求如此
			// if(this.userIndex){
			// 	const {style, styleId, companyId} =this.userList[this.userIndex]
			// 	putCardStyleUpdate( {
			// 		"organisationId": companyId,
			// 		"styleId": styleId,
			// 		// "themeId": style
			// 	}).then(res=>{

			// 	})
			// }
			this.enterLoading = true;
			hotTextPublish({
				articleSource: this.detail.articleSource,
				author: this.detail.author,
				// "cid": "",
				contentImg: this.detail.contentImg,
				time: this.detail.time,
				content: this.detail.content,
				img: this.detail.img,
				title: this.detail.title,
				url: this.text
			})
				.then((res) => {
					if (res.data) {
						if (this.isApp) {
							this.step = 0;
							this.loading = false;
							this.text = '';
							const data = {
								type: 'hotArticleDetail',
								url: `${location.origin}${location.pathname}#/hotArticle/detail?id=${res.data}&pageType=2`
							};
							this.$bridge.callHandler('recruitHandler', data, () => {
								console.log('recruitHandler', '返回');
							});
						} else {
							getApp().globalData.hotArticleTemp = {};
							this.$pageTo(
								`/hotArticle/detail?id=${res.data}&pageType=2`,
								'redirectTo'
							);
						}
						this.enterLoading = false;
					}
				})
				.catch((err) => {
					this.enterLoading = false;
				});
		}, 2000),
		radioTap(item, index) {
			this.userList.filter((item) => {
				item.check = false;
			});
			this.userIndex = index;
			this.userList[index].check = true;
		},
		closePage() {
			uni.navigateBack();
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep .u-tabbar__content {
	background-color: var(--controllerBgColor);
	border: none;
	.u-tabbar__content__item-wrapper {
		height: 120rpx;
	}
}
.step1 {
}
.step2 ::v-deep .u-tabbar__content {
	background-color: #fff;
}
.page-wrap {
	min-height: calc(100vh);
}

.wrap {
	padding: 40rpx;
	position: relative;
	z-index: 1;
}
.gather {
	padding: 34rpx 0 0;
}
.gather-text {
	padding: 0;
}
.gather-text .bd {
	padding: 0 0 20rpx;
}
// .gather-text .bd{padding: 34rpx 0 20rpx;}
.item {
	padding: 10rpx 0;
}
.text {
	padding: 24rpx;
	width: 622rpx;
	height: 270rpx;
	font-size: 28rpx;
	background: var(--viewBgColor);
	line-height: 40rpx;
	border-radius: 12rpx;
}
.item .num {
	margin-right: 18rpx;
	width: 40rpx;
	height: 40rpx;
	background: var(--viewBgColor);
	border-radius: 50%;
}
.item .u-icon {
	margin: 0 14rpx 0 0;
}
.article-card {
	background-color: var(--viewBgColor);
	padding: 24rpx;
	border-radius: 8rpx;
}
.article-card .pic {
	width: 100rpx;
	height: 100rpx;
	margin-right: 24rpx;
	border-radius: 8rpx;
	overflow: hidden;
}
.gather-analyze {
	padding: 24rpx 28rpx;
	border-radius: 12rpx;
	position: relative;
	background-color: var(--viewBgColor);
}
.gather-analyze .pic {
	margin-right: 18rpx;
	width: 104rpx;
	height: 104rpx;
	border-radius: 12rpx;
}
.gather-analyze .close {
	position: absolute;
	right: 28rpx;
	top: 24rpx;
}
.article-relevance {
	margin: 54rpx 0 0;
}
.article-relevance .bd {
	padding: 32rpx 0 0;
}
.user-item {
	position: relative;
	padding-right: 24rpx;
	margin-bottom: 40rpx;
	border-radius: 8rpx;
	background-color: var(--viewBgColor);
	overflow: hidden;
}
.avatar {
	width: 230rpx;
	height: 214rpx;
	overflow: hidden;
	background-color: #fff;
}
.line {
	position: absolute;
	left: 215rpx;
	top: 0;
	width: 40rpx;
	height: 224rpx;
	background-color: var(--viewBgColor);
	transform: rotate(6deg);
	z-index: 1;
}
.detail_msg {
	position: relative;
	z-index: 2;
}
.info {
	padding: 28rpx 0 0 32rpx;
	color: var(--contentFontDarkColor);
}
.info .company {
	margin-top: 26rpx;
}
.info .bwfont {
	margin-right: 16rpx;
	font-size: 28rpx;
}
.name {
	color: var(--titleFontColor);
}
.radio {
	position: relative;
}
.icon {
	position: absolute;
	right: 0;
	top: 0;
	width: 38rpx;
	height: 36rpx;
}
.radio {
	width: 32rpx;
	height: 32rpx;
	border: 1px solid #ffd9b5;
	border-radius: 50%;
}
// .fixed-bottom{position:fixed;bottom:0;left: 0;}
.bottom-btn {
	padding: 0 40rpx;
	width: 100%;
}
.btn-preview {
	background: rgba(255, 217, 181, 0.1);
	width: 210rpx;
}
.btn {
	height: 76rpx;
}
.btn + .btn {
	margin-left: 36rpx;
}

.userInfo {
	margin: 0 0 40rpx;
	height: 214rpx;
	border-radius: 8rpx;
	background: #f4f8fb;
	align-items: center;
	position: relative;
	overflow: hidden;
	.avatar {
		height: 214rpx;
		width: 230rpx;
		// border: 1px dashed #ccc;
	}
	.line {
		position: absolute;
		left: 215rpx;
		top: 0;
		width: 40rpx;
		height: 224rpx;
		background-color: #f4f8fb;
		transform: rotate(6deg);
		z-index: 1;
	}
	.detail_msg {
		padding: 28rpx;
		height: 100%;
		position: relative;
		z-index: 2;
		.name {
			font-weight: bold;
			line-height: 44rpx;
			color: #111018;
		}
		.user_msg {
			color: #6d6d76;
			line-height: 46rpx;
			.icon_txt {
				font-size: 26rpx;
				margin-right: 10rpx;
			}
		}
	}
}
.article {
	background-color: #fff;
	padding: 20rpx 40rpx 40rpx;
	width: 750rpx;
	overflow: hidden;
	padding-bottom: 230rpx;
	.title {
		// padding: 0 40rpx;
		line-height: 54rpx;
		color: #000;
	}
	.info {
		padding: 0 40rpx 20rpx;
		color: var(--contentFontDarkColor);
		margin: 18rpx 0;
		.txt_msg {
			margin-right: 28rpx;
		}
	}
	.line_box {
		height: 1px;
		background: #1e222f;
		margin: 38rpx 0;
	}
	.detail {
		// padding-top: 40rpx;
		// padding: 0 40rpx 0 40rpx;
		text-align: justify;
	}
	.reminder {
		margin-top: 40rpx;
		color: var(--contentFontDarkColor);
		line-height: 40rpx;
	}
	::v-deep .content {
		img {
			max-width: 100%;
			height: auto;
		}
	}
}
</style>
